<?php
namespace app\admin\controller;

use app\common\model\mysql\AdminUser;
use think\Exception;
use think\facade\View;

class Login extends AdminBase {
    protected function initialize()
    {
        if ($this->isLogin()){
            return $this->redirect(url('index/index'));
        }
    }

    public function index() {
        return  View::fetch();
    }

    public function check() {
        if (!$this->request->isPost()){
            return show(config('status.error'), '请求方式错误');
        }
        // 参数检验 验证机制 1.原生方式  2.tp6 验证机制
        $data = [
            'username'=>$this->request->param('username', '', 'trim'),
            'password'=>$this->request->param('password', '', 'trim'),
            'captcha'=>$this->request->param('captcha', '', 'trim'),
        ];
        $validate = new \app\admin\validate\AdminUser();
        if ( ! $validate->check($data)){
            return show(config('status.error'), $validate->getError());
        }

        // 需要校验验证码,使用validate验证机制
        /*if ( ! captcha_check($captcha)){
            return show(config('status.error'), '验证码错误');
        }*/

        try {
            $result = \app\admin\business\AdminUser::login($data);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
        if ($result) {
            return show(config('status.success'), '登录成功');
        }
        return show(config('status.error'), '登录失败');
    }
}